package com.my.admin.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * @author 25755
 */
@Configuration
@Slf4j
public class RedisCacheConfig extends CachingConfigurerSupport {

    @Override
    public KeyGenerator keyGenerator() {
        return (o, method, objects) -> {
            //格式化缓存key字符串
            StringBuilder sb = new StringBuilder();
            //追加类名
            sb.append(o.getClass().getName()).append(":");
            //追加方法名
            sb.append(method.getName()).append(":");
            //遍历参数并且追加
            for (Object obj : objects) {
                if(obj instanceof IPage) {
                    IPage<?> page = ((IPage<?>) obj);
                    sb.append(page.getCurrent()).append("-").append(page.getSize());
                }else if(obj instanceof QueryWrapper){
                    QueryWrapper<?> qw = (QueryWrapper<?>) obj;
                    sb.append(qw.getTargetSql()).append(":").append(qw.getParamNameValuePairs());
                }else {
                    sb.append(obj.toString());
                }
            }
            log.info("调用Redis缓存Key : " + sb.toString());
            return sb.toString();
        };
    }

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
        configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).entryTtl(Duration.ofDays(30));
        return configuration;
    }

}
